<template>
  <el-dialog :title="form.id ? $t('user.ModifyUser'): $t('user.AddUser') " :visible.sync="formVisible" width="600px"
    append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('user.Nickname')" prop="nickName">
            <el-input v-model="form.nickName" :placeholder="$t('user.InputNickname')" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('State')">
            <dict-number-radio v-model="form.status" :dict="dict.type.sys_normal_disable" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('Department')" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
              :placeholder="$t('user.SelectDepartment')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Role')">
            <el-select v-model="form.roleIds" multiple :placeholder="$t('user.SelectRole')" @change="roleChange">
              <el-option v-for="item in roleOptions" :key="item.roleId" :label="$t('role.ROLE.'+item.roleKey)"
                :value="item.roleId" :disabled="item.status == 1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="form.userId == undefined" :label="$t('user.Username')" prop="userName">
            <el-input v-model="form.userName" :placeholder="$t('user.InputUsername')" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.userId == undefined" :label="$t('user.UserPassword')" prop="password">
            <el-input v-model="form.password" :placeholder="$t('user.InputPassword')" type="password" maxlength="20"
              show-password />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('user.Remarks')">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('user.InputContent')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t("OK") }}</el-button>
      <el-button @click="cancel">{{ $t("Cancel") }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import systemUserAPI from "@/api/system/user";

  export default {
    name: 'UserFormDialog',
    dicts: ["sys_normal_disable"],
    data() {
      return {
        deptOptions: [],
        postOptions: [],
        roleOptions: [],
        lastRoleId: null,
        form: {},
        formVisible: false,
        rules: {
          userName: [{
              required: true,
              message: this.$t("user.UsernameNull"),
              trigger: "blur",
            },
            {
              min: 2,
              max: 20,
              message: this.$t("user.UsernameLong"),
              trigger: "blur",
            },
          ],
          nickName: [{
            required: true,
            message: this.$t("user.NicknameNULL"),
            trigger: "blur",
          }, ],
          password: [{
              required: true,
              message: this.$t("user.PasswordNull"),
              trigger: "blur",
            },
            {
              min: 5,
              max: 20,
              message: this.$t("user.PasswordLong"),
              trigger: "blur",
            },
          ],
          deptId: [{
            required: true,
            message: this.$t("user.DepartmentNull"),
            trigger: "blur",
          }],
          roleIds: [{
            required: true,
            message: this.$t("user.RoleNull"),
            trigger: "blur",
          }],
          email: [{
            type: "email",
            message: this.$t("user.InputCorrectEmail"),
            trigger: ["blur", "change"],
          }, ],
          phonenumber: [{
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t("user.InputCorrectPhone"),
            trigger: "blur",
          }, ]
        },
      }
    },
    created() {
      const vm = this
      systemUserAPI.getSetting().then(data => {
        vm.postOptions = [].concat(data.posts)
        vm.roleOptions = [].concat(data.roles)
      })
    },
    methods: {
      show(user, deptOptions) {
        this.resetForm("form");
        this.form = Object.assign({}, user)
        this.lastRoleId = user.roleIds[0]
        this.deptOptions = [].concat(deptOptions)
        this.formVisible = true
      },
      roleChange(value) {
        if (value && value.length > 0) {
          this.lastRoleId = value[0]
          return
        }
        this.$message({
          type: 'warning',
          message: this.$t('user.AtLeastOnCharacter')
        })
        const {
          lastRoleId
        } = this
        this.form.roleIds = [lastRoleId]
      },
      cancel() {
        this.formVisible = false;
      },
      submitForm: function () {
        const vm = this
        this.$refs["form"].validate((valid) => {
          if (!valid) {
            return
          }
          if (vm.form.userId != undefined) {
            systemUserAPI.updateUser(vm.form).then((response) => {
              vm.$modal.msgSuccess(vm.$t("ModifySuccessful"));
              vm.formVisible = false;
              vm.$emit('submit');
            });
            return
          }
          systemUserAPI.addUser(vm.form).then((response) => {
            vm.$modal.msgSuccess(vm.$t("AddSuccessful"));
            vm.formVisible = false;
            vm.$emit('submit');
          });
        });
      }
    }
  }

</script>
